﻿ 
using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Authentication;
using System.Threading.Tasks;
using Talk.Extensions;
using Aspose.Cells;

using System.Drawing;
using System.Drawing.Imaging;

namespace Meiam.System.Common
{
    public static class MailHelper
    {
        /// <summary>
        /// 导出文件（图片）
        /// </summary>
        public static bool ExportPng(string fileName, string path)
        {
            try
            {
                // Load Excel file
               

                var workbook = new Workbook(path);
                // Get reference of desired worksheet
                var worksheet = workbook.Worksheets[0];
                // Set options for output image
                var options = new Aspose.Cells.Rendering.ImageOrPrintOptions()
                {
                  //  AllColumnsInOnePagePerSheet=true,
                    OnePagePerSheet = true,
                    ImageFormat = ImageFormat.Png
                };
                // Convert Excel worksheet to SVG
                var renderer = new Aspose.Cells.Rendering.SheetRender(worksheet, options);
                 renderer.ToImage(0,fileName);
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }

        public static bool SendMail(int sendType,string pushCode,string type,string title, string content,string attachment, MailEntity mailInfo = null,OAEntity oaInfo=null)
        {
            try
            {
                if(mailInfo == null)
                {
                    mailInfo =   FileConfig.GetMailInfo();
                    if (mailInfo.MailPwd.IsNullOrWhiteSpace() ||
                        mailInfo.MailFrom.IsNullOrWhiteSpace() ||
                        mailInfo.MailHost.IsNullOrWhiteSpace())
                    {
                        throw new Exception("请先在 [/seting] 页面配置邮箱设置。");
                    }
                }

                // MimeMessage代表一封电子邮件的对象
                var message = new MimeMessage();
                // 添加发件人地址 Name 发件人名字 sender 发件人邮箱
                message.From.Add(new MailboxAddress(mailInfo.MailFrom, mailInfo.MailFrom));
                string mailTos = string.Empty;
                foreach(var mailto in mailInfo.MailTos)
                {
                    if (mailto.Type == type) mailTos= mailto.Value;
                }
                if (string.IsNullOrEmpty(mailTos)&& sendType==0) return false;

                if (!string.IsNullOrEmpty(mailTos))
                {
                    // 添加收件人地址
                    foreach (var mailTo in mailTos.Replace("；", ";").Replace("，", ";").Replace(",", ";").Split(';'))
                    {
                        message.To.Add(new MailboxAddress(mailTo, mailTo));
                    }
                }
              
                //  message.To.Add(new MailboxAddress("", mailInfo.MailTo));
                // 设置邮件主题信息
                message.Subject = title;
                // 设置邮件内容
               // var bodyBuilder = new BodyBuilder() { HtmlBody = content };
                var multipart = new MimeKit.Multipart("mixed");
                var plain = new TextPart("plain")
                {
                    Text = content
                };
                var alternative = new Multipart("alternative");
                alternative.Add(plain);
                multipart.Add(alternative);

                if (!string.IsNullOrEmpty(attachment))
                {
                    if (!File.Exists(attachment)) return false;

                    string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                    string pngName = Path.GetFileNameWithoutExtension(attachment) +"_"+ timestamp + ".jpg";
                    string pngPath = Path.GetDirectoryName(attachment) +"\\" + pngName;
                    var result= ExportPng(pngPath, attachment);

                    if (result)
                    {
                        if (sendType == 1)
                        {
                            if (oaInfo == null)
                            {
                                oaInfo = FileConfig.GetOAInfo();
                                if (oaInfo.OATos.Count < 1)
                                {
                                    throw new Exception("请先配置OA设置。");
                                }
                            }
                            string oaTos = string.Empty;
                            foreach (var oato in oaInfo.OATos)
                            {
                                if (oato.Type == type)
                                {
                                    oaTos = oato.Value;
                                    break;
                                }
                            }

                            //发送OA
                            string OAFileUrlPath = "http://oapush.gokinsolar.com:18888/files/resources/" + pngName;
                            OAPushHelper.Push(pushCode, type, OAFileUrlPath, OAFileUrlPath, oaTos,content+"<br/>"+ "请点击阅读详情");
                        }

                        var attachment0 = new MimeKit.MimePart("image", "png")
                        {
                            ContentObject = new MimeKit.ContentObject(File.OpenRead(pngPath), MimeKit.ContentEncoding.Default),
                            ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment),
                            ContentTransferEncoding = MimeKit.ContentEncoding.Base64,
                            FileName = pngName
                        };
                        multipart.Add(attachment0);
                    }
                   
                    // byte[] myFileAsByteArray = File.ReadAllBytes(attachment);
                    // bodyBuilder.Attachments.Add(attachment, myFileAsByteArray, new ContentType("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
                }

                if (sendType != 0) return true;

                message.Body = multipart;
                using (var client = new SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    // Note: since we don't have an OAuth2 token, disable 
                    // the XOAUTH2 authentication mechanism. 
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    client.CheckCertificateRevocation = false;
                    //client.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
                    client.Connect(mailInfo.MailHost, 25, MailKit.Security.SecureSocketOptions.None);
                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate(mailInfo.MailFrom, mailInfo.MailPwd);
                    client.Send(message);
                    client.Disconnect(true);
                    return true;
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("邮件推送异常,原因:" + ex.Message);
            }
            return false;
        }
        //public static async Task<bool> SendMail(string title, string content, MailEntity mailInfo = null)
        //{
        //    if (mailInfo == null)
        //    {
        //        mailInfo = await FileConfig.GetMailInfoAsync();
        //        if (mailInfo.MailPwd.IsNullOrWhiteSpace() ||
        //            mailInfo.MailFrom.IsNullOrWhiteSpace() ||
        //            mailInfo.MailHost.IsNullOrWhiteSpace())
        //        {
        //            throw new Exception("请先在 [/seting] 页面配置邮箱设置。");
        //        }
        //    }

        //    var message = new MimeMessage();
        //    message.From.Add(new MailboxAddress(mailInfo.MailFrom, mailInfo.MailFrom));
        //    foreach (var mailTo in mailInfo.MailTo.Replace("；", ";").Replace("，", ";").Replace(",", ";").Split(';'))
        //    {
        //        message.To.Add(new MailboxAddress(mailTo, mailTo));
        //    }
        //    message.Subject = string.Format(title);
        //    message.Body = new TextPart("html")
        //    {
        //        Text = content
        //    };
        //    using (var client = new MailKit.Net.Smtp.SmtpClient())
        //    {
        //        await client.ConnectAsync(mailInfo.MailHost, 465, false);
        //        await client.AuthenticateAsync(mailInfo.MailFrom, mailInfo.MailPwd);
        //        await client.SendAsync(message);
        //        await client.DisconnectAsync(true);
        //    }
        //    return true;
        //}

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="Name">发件人名字</param>
        /// <param name="receive">接收邮箱</param>
        /// <param name="sender">发送邮箱</param>
        /// <param name="password">邮箱密码</param>
        /// <param name="host">邮箱主机</param>
        /// <param name="port">邮箱端口</param>
        /// <param name="subject">邮件主题</param>
        /// <param name="body">邮件内容</param>
        /// <returns></returns>
        public static async Task<bool> SendMailAsync(string Name, string receive, string sender, string password, string host, int port, string subject, string body,string attachment)
        {
            try
            {
                // MimeMessage代表一封电子邮件的对象
                var message = new MimeMessage();
                // 添加发件人地址 Name 发件人名字 sender 发件人邮箱
                message.From.Add(new MailboxAddress(Name, sender));
                // 添加收件人地址
                message.To.Add(new MailboxAddress("", receive));
                // 设置邮件主题信息
                message.Subject = subject;
                // 设置邮件内容
                var bodyBuilder = new BodyBuilder() { HtmlBody = body };

                // you can either create MimeEntity object(s)
                // this might get handy in case you want to pass multiple attachments from somewhere else
                if (!string.IsNullOrEmpty(attachment))
                {
                    byte[] myFileAsByteArray = File.ReadAllBytes(attachment);
                    
                    bodyBuilder.Attachments.Add("报表.xlsx", myFileAsByteArray, new ContentType("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
                }
                //var attachments = new List<MimeEntity>
                //{
                //    // from file
                //    MimeEntity.Load("myFile.pdf"),
                //    // file from stream
                //    MimeEntity.Load(new MemoryStream(myFileAsByteArray)),
                //    // from stream with a content type defined
                //    MimeEntity.Load(new ContentType("application","pdf"), new MemoryStream(myFileAsByteArray))
                //};

                //// append previously created attachments
                //foreach (var attachment in attachments)
                //{
                //    bodyBuilder.Attachments.Add(attachment);
                //}

                // or add file directly - there are a few more overloads to this




                message.Body = bodyBuilder.ToMessageBody();


                using (var client = new SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    // Note: since we don't have an OAuth2 token, disable 
                    // the XOAUTH2 authentication mechanism. 
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    client.CheckCertificateRevocation = false;
                    //client.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
                    client.Connect(host, port, MailKit.Security.SecureSocketOptions.Auto);
                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate(sender, password);
                    await client.SendAsync(message);
                    client.Disconnect(true);
                    return true;
                }
            }
            catch (Exception ex)
            {
            }
            return false;
        }

        public static async Task<bool> SendMail(string title, string content, string mailTo)
        {
            var info = await FileConfig.GetMailInfoAsync();
            if (info.MailPwd.IsNullOrWhiteSpace() || info.MailFrom.IsNullOrWhiteSpace() || info.MailHost.IsNullOrWhiteSpace())
                throw new Exception("请先在 [/seting] 页面配置邮箱设置。");

            return false;
            //info.MailTos = new List<MailToEntity> {  }.Add(mailTo);
            //return await SendMailAsync(info.MailFrom, info.MailTo, info.MailFrom, info.MailPwd, info.MailHost, 465, title, content,string.Empty);
            //  return await SendMail(title, content, info);
        }
    }
}
